package com.example.zyl.common.query.query;

import cn.hutool.extra.spring.SpringUtil;
import com.example.zyl.api.entity.SysDict;
import com.example.zyl.api.service.SysDictService;
import com.example.zyl.common.query.annotation.ApiDict;
import com.example.zyl.common.utils.ToolUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.List;

public interface BaseDictConvertDto {

    Logger log = LoggerFactory.getLogger(BaseDictConvertDto.class);

    SysDictService dictService = SpringUtil.getBean(SysDictService.class);

    /**
     * 转换字典数据
     */
    default void convert() {

        //获取所有需要转换的字段
        List<Field> dictFields = BaseQueryDto.getQueryFields(this.getClass());
        //遍历所有需要转换的字段
        for (Field field : dictFields) {
            try {
                field.setAccessible(true);
                //获取字段值
                Object value = field.get(this);
                //获取字段名
                String fieldName = field.getName();
                //获取字段的注解
                ApiDict dictConvert = field.getAnnotation(ApiDict.class);
                if (dictConvert != null) {
                    //判断是否有值
                    if (ToolUtils.isNotEmpty(value)) {
                        //获取转换的字典类
                        String name = ToolUtils.isEmpty(dictConvert.type()) ? fieldName : dictConvert.type();
                        //获取转换的字典字段名
                        SysDict sysDict = dictService.getDictByCode(name, value.toString());
                        if (sysDict != null) {
                            field.set(this, sysDict.getDictValue());
                        }
                    }
                }
            } catch (IllegalAccessException e) {
                log.error("转换字典数据异常 ===> {}", e.getMessage(), e);
            }
        }
    }
}
